import {SafeAreaView, FlatList} from 'react-native';
import Banner from './Banner';
import {styles} from '../const';
import {observer} from 'mobx-react-lite';
import {useHomeStore} from '../../../mobx';
import MainModel from './MainModle';
import {Empty} from '../../../components';
import {useEffect, useRef} from 'react';
import QuickNav from './QuickNav';
import {getItem} from '../../../utils';
import {homeType} from '../../../constants';

type Idx = 0 | 1 | 2;

const _renderItem = ({item, scrollToTop, navigation, idx}: any) => {
  if (item.Id === 'banner') {
    return Array.isArray(item?.list) && item.list.length > 0 ? (
      <Banner {...item} navigation={navigation} />
    ) : null;
  }
  if (item.Id === 'quickNav') {
    return <QuickNav navigation={navigation} />;
  }
  if (item.Id === 'noData') {
    return <Empty type="domine" />;
  }
  return (
    <MainModel
      {...item}
      scrollToTop={scrollToTop}
      navigation={navigation}
      typeId={idx + 1}
    />
  );
};

const Content = observer((props: any) => {
  const {navigation, idx} = props;
  const {bannerList, groupList, setCurData} = useHomeStore();
  const flatListRef = useRef<any>(null);

  useEffect(() => {
    getItem(homeType[idx as Idx])
      .then((data: any) => {
        setCurData(data);
      })
      .catch(() => {});
  }, [idx]);

  // 回到顶部
  const scrollToTop = () => {
    if (flatListRef.current) {
      flatListRef.current.scrollToIndex({index: 0, viewPosition: 0});
    }
  };

  return (
    <SafeAreaView style={styles.tabContent}>
      <FlatList
        ref={flatListRef}
        data={[
          {Id: 'banner', list: bannerList},
          {Id: 'quickNav'},
          ...groupList,
          {Id: 'noData'},
        ]}
        renderItem={info =>
          _renderItem({...info, scrollToTop, navigation, idx})
        }
        keyExtractor={item => `${item.Id}`}
      />
    </SafeAreaView>
  );
});

export default Content;
